﻿package problems.producerconsumer;

import problems.BenchmarkSemaphore;
import helpers.IAction;


/// <summary>
/// This class represents Downey's suggested solution to the Producer Consumer problem.
/// </summary>
public class ProducerConsumerSolution extends AbstractProducerConsumer
{
    private final BenchmarkSemaphore mutex;

    /// <summary>
    /// A BenchmarkSemaphore representing the number of items that have been produced
    /// </summary>
    private final BenchmarkSemaphore items;
     
    public ProducerConsumerSolution()
    {
        mutex = new BenchmarkSemaphore(1);
        //0 items have been produced at the start
        items = new BenchmarkSemaphore(0);
    }

    @Override
    public void consume()
    {
        items.waitOne();
        mutex.waitOne();
        IAction action = getBuffer().remove();
        mutex.release();
        action.invoke();
    }

    @Override
    public void produce(IAction action)
    {
        mutex.waitOne();
        getBuffer().add(action);
        mutex.release();
        items.release();
    }
}